<?php

class CartsController extends AppController {

    var $name = 'Carts';
    var $uses = array('Product', 'Cart', 'Wishlist', 'Paymentmethod', 'Shipping', 'Order');
    var $components = array('Session', 'Cookie', 'GoogleCheckout','Paypal');
    var $editcartlink = "http://stage.authenticavenue.com/carts/view_cart";

    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allowedActions = array('totalitem_cart', 'addtocart', 'view_cart', 'fetchcart', 'updatequantity', 'removecartitem', 'fetch_shipping_method');
    }

    //Add to cart
    function addtocart($id=null, $id2=null, $id3=null, $id4=null) {
        $this->layout = false;
        $uniqueIDCoookie = $this->Cookie->read('uniqueID');
        if ($this->Auth->User('id'))
            $conditions = array("Cart.user_id" => $this->Auth->User('id'), 'Cart.unique_id' => $uniqueIDCoookie, "Cart.product_id" => $id, "Cart.payment_status" => 0);
        else
            $conditions = array('Cart.unique_id' => $uniqueIDCoookie, "Cart.product_id" => $id, "Cart.status" => 0);

        $alreadyInCart = $this->Cart->find("all", array("conditions" => $conditions));

        if ($alreadyInCart) {
            $return['msg'] = "You already add this product to your cart.";
        } else {
            $this->Product->id = $id;
            $product = $this->Product->read();
            $newPrice = $this->Product->commition($product, $this->Auth->User('id'));
            $this->data['Cart']['product_cost'] = $newPrice['price'];
            $this->data['Cart']['quantity'] = $id2;
            $this->data['Cart']['product_id'] = $id;
            $this->data['Cart']['seller_id'] = $product['Product']['user_id'];
            $this->data['Cart']['unique_id'] = $uniqueIDCoookie;
            $this->data['Cart']['add_date'] = date("Y-m-d H:i:s");
            if ($this->Auth->User('id')) {
                $this->data['Cart']['user_id'] = $this->Auth->User('id');
                $this->data['Cart']['status'] = 1;
            }

            $this->Cart->create();
            if ($this->Cart->save($this->data)) {
                if ($id4 == null) {
                    $this->Wishlist->delete($id3);
                    $return['wid'] = $id3;
                } else {
                    $this->loadModel('Negotiation');
                    if ($id4 == 1) {
                        $negid = $this->Negotiation->find('first', array('fields' => array('Negotiation.id'), 'conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $id, 'Negotiation.status' => 'Accepted')));
                    } elseif ($id4 == 2) {
                        $negid = $this->Negotiation->find('first', array('fields' => array('Negotiation.id'), 'conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $id, 'Negotiation.status' => 'Pending')));
                    }
                    $this->Negotiation->id = $negid['Negotiation']['id'];
                    $this->Negotiation->saveField('cart_chk', '1');
                }
                $return['msg'] = "You have successfully added the product to your cart.";
            } else {
                $return['msg'] = "Opps there is an error while trying to add product to your cart.";
            }
        }

        echo json_encode($return);
        $this->autoRender = false;
    }

    //Add to wishlists
    function addtowishlists($id=null, $id2=null) {
        $this->layout = false;

        $conditions = array('Wishlist.product_id' => $id, "Wishlist.user_id" => $this->Auth->User('id'));
        $alreadyInWishlist = $this->Wishlist->find("count", array("conditions" => $conditions));

        if ($alreadyInWishlist > 0) {
            $return['msg'] = "You already add this product to your wishlists.";
        } else {

            $this->data['Wishlist']['product_id'] = $id;
            $this->data['Wishlist']['user_id'] = $this->Auth->User('id');
            $this->data['Wishlist']['add_date'] = date("Y-m-d H:i:s");

            $this->Wishlist->create();
            if ($this->Wishlist->save($this->data)) {
                $return['msg'] = "You have successfully added the product to your Wishlists.";
            } else {
                $return['msg'] = "Opps there is an error while trying to add product to your Wishlists.";
            }
        }

        echo json_encode($return);
        $this->autoRender = false;
    }

    //view  wishlists
    function wishlist() {
        $this->layout = "innerhome";
        $this->Wishlist->recursive = 2;
        $this->Wishlist->Behaviors->attach('Containable');
        $wishlists = $this->Wishlist->find("all", array(
            'conditions' => array('Wishlist.user_id' => $this->Auth->User('id')),
            'order' => array('Wishlist.id' => 'desc'),
            'contain' => array('Product.id', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Product.products_expiredDate', 'Product.products_thumbnailImage', 'Product.User')
                ));
        $this->set('wishlists', $wishlists);
    }

    //Remove from wishlist
    function removefromwishlist($id=null) {
        $this->layout = false;
        $this->Wishlist->recursive = -1;
        $notes = $this->Wishlist->findBYId($id);
        $this->loadModel('Note');

        if ($this->Note->query('DELETE FROM authentic_notes WHERE user_id=' . $notes['Wishlist']['user_id'] . ' AND product_id=' . $notes['Wishlist']['product_id'])) {

            if ($this->Wishlist->delete($id)) {
                $return['msg'] = "The Product has been successfully removed from the wishlist.";
                $return['wid'] = $id;
            } else {
                $return['msg'] = "The product could not be removed. Please, try again.";
            }
        } else {
            $return['msg'] = "The product could not be removed. Please, try again.";
        }
        echo json_encode($return);
        $this->autoRender = false;
    }

    //View Cart
    function view_cart() {
        $this->layout = "carthome";
        $uniqueIDCoookie = $this->Cookie->read('uniqueID');
        if ($this->Auth->User('id'))
            $conditions = array("Cart.user_id" => $this->Auth->User('id'), 'Cart.product_id >' => 0, 'Cart.payment_status' => 0);
        else
            $conditions = array('Cart.unique_id' => $uniqueIDCoookie, 'Cart.product_id >' => 0);

        $this->Cart->recursive = 2;
        $sellers = $this->Cart->find("all", array("conditions" => $conditions, 'group' => 'Product.user_id'));

        $this->Cart->recursive = 2;
        foreach ($sellers as $seller):
            $conditions['Product.user_id'] = $seller['Product']['user_id'];
            $carts_seller[$seller['Product']['user_id']] = $seller['User']['username'];
            $this->Cart->Behaviors->attach('Containable');
            $this->Cart->contain('Shipping.shipping_method', 'User.id', 'User.Country.name', 'User.State.name', 'User.City.name', 'Product.id', 'Product.products_weight', 'Product.user_id', 'Product.category_id', 'Product.products_title', 'Product.products_price', 'Product.products_quantity', 'Product.use_paypal', 'Product.use_google_checkout', 'Product.tax_us', 'Product.products_commission', 'Product.products_commissionType', 'Product.ProductShipping', 'Product.ProductShipping.Shipping', 'Product.ProductInternationalShipping.Shipping', 'Product.ProductInternationalShipping', 'Product.Salestax', 'Product.User.username');
            $carts[$seller['Product']['user_id']] = $this->Cart->find("all", array("conditions" => $conditions));
        endforeach;
        //pr($carts);
        $this->set(compact('carts_seller', 'carts'));
    }

    //Fetch Cart
    function fetchcart() {
        $this->layout = false;
        $uniqueIDCoookie = $this->Cookie->read('uniqueID');
        if ($this->Auth->User('id'))
            $conditions = array("Cart.user_id" => $this->Auth->User('id'), 'Cart.product_id >' => 0, 'Cart.payment_status' => 0);
        else
            $conditions = array('Cart.unique_id' => $uniqueIDCoookie, 'Cart.product_id >' => 0);

        $this->Cart->recursive = 2;
        
        $sellers = $this->Cart->find("all", array("conditions" => $conditions, 'group' => 'Product.user_id'));
        //pr($sellers);
        $this->Cart->recursive = 2;
        foreach ($sellers as $seller):
            $conditions['Product.user_id'] = $seller['Product']['user_id'];
            $carts_seller[$seller['Product']['user_id']] = $seller['Product']['User']['username'];
            $this->Cart->Behaviors->attach('Containable');
            $this->Cart->contain('Product.Category.shipping_weight', 'Shipping.shipping_method', 'User.id', 'User.Country.name', 'User.State.name', 'User.City.name', 'Product.id', 'Product.products_weight', 'Product.user_id', 'Product.category_id', 'Product.products_title', 'Product.products_price', 'Product.products_quantity', 'Product.use_paypal', 'Product.use_google_checkout', 'Product.tax_us', 'Product.products_commission', 'Product.products_commissionType', 'Product.ProductShipping', 'Product.ProductShipping.Shipping', 'Product.ProductInternationalShipping.Shipping', 'Product.ProductInternationalShipping', 'Product.Salestax', 'Product.User.username');
            $carts[$seller['Product']['user_id']] = $this->Cart->find("all", array("conditions" => $conditions));
        endforeach;
        //pr($carts);
        $this->set(compact('carts_seller', 'carts'));
    }

    //Update quantity in cart
    function updatequantity() {
        $this->layout = false;
        $this->autoRender = false;

        //check quantity
        if ($this->data['Cart']['quantity'] == 0 || $this->data['Cart']['quantity'] < 0) {
            $return['msg'] = 'Please enter a valid number';
            $return['ok'] = "No";
            echo json_encode($return);
            return;
        }
        $carts = $this->Cart->findById($this->data['Cart']['cart_id']);
        if ($this->Auth->User('id') > 0) {
            $this->loadModel('AddressBook');
            $this->loadModel('AddressBookField');
            $this->AddressBook->recursive = 2;
            $shipping_address = $this->AddressBook->find('first', array('conditions' => array('AddressBook.user_id' => $this->Auth->User('id'), 'use_in_cart' => "yes")));
            if ($shipping_address)
                $country = $shipping_address['AddressBookField']['country_id'];
            else
                $country = $this->Session->read('Auth.User.country_id');
            if ($country == 1) {
                $this->Shipping->recursive = -1;
                $shippings = $this->Shipping->findById($this->data['Cart']['shipping_method']);
                $products_weight = $carts['Product']['products_weight'];
                $category_id = $carts['Product']['category_id'];
                $shipping_costs = $this->Category->findById($category_id);
                $shipping_cost = $shipping_costs['Category']['shipping_cost'];
            } else {
                $this->Shipping->recursive = -1;
                $shippings = $this->Shipping->findById($this->data['Cart']['shipping_method']);
                $products_weight = $carts['Product']['products_weight'];
                $category_id = $carts['Product']['category_id'];
                $this->loadModel('ProductInternationalShipping');
                $shipping_costs = $this->ProductInternationalShipping->find("first", array("conditions" => array("ProductInternationalShipping.shipping_id" => $this->data['Cart']['shipping_method'], "ProductInternationalShipping.product_id" => $carts['Product']['id'])));
                $shipping_cost = $shipping_costs['ProductInternationalShipping']['shipping_cost'];
            }

            //calulate changed price due to commintion and negotiation
            $userId = $carts['User']['id'];
            $newPrice = $this->Product->commition($carts, $this->Auth->User('id'));
            $carts['Product']['products_price'] = $newPrice['price'];
            $carts['User']['id'] = $userId;

            if ($this->data['Cart']['quantity'] > $carts['Product']['products_quantity']) {
                $return['ok'] = "No";
                $return['msg'] = "Sorry, Quantity is not available that you have wanted to add in your Cart.";
            } else {
                $this->data['Cart']['id'] = $this->data['Cart']['cart_id'];
                $this->data['Cart']['shipping_cost'] = $shipping_cost;
                $this->data['Cart']['shipping_id'] = $this->data['Cart']['shipping_method'];
                $this->Cart->save($this->data);
                $return['msg'] = "Your cart has been successfully updated.";
                $return['ok'] = "Yes";
            }
        } else {
            if ($this->data['Cart']['quantity'] > $carts['Product']['products_quantity']) {
                $return['ok'] = "No";
                $return['msg'] = "Sorry, Quantity is not available that you have wanted to add in your Cart.";
            } else {
                $this->data['Cart']['id'] = $this->data['Cart']['cart_id'];
                $this->Cart->save($this->data);
                $return['msg'] = "Your cart has been successfully updated.";
                $return['ok'] = "Yes";
            }
        }
        echo json_encode($return);
    }

    //Removed Item from cart
    function removecartitem($id=null) {
        $this->layout = false;
        if ($this->Cart->delete($id)) {
            $return['msg'] = "Yes";
            $return['CartID'] = $id;
        } else {
            $return['msg'] = "No";
        }
        $this->redirect('view_cart');
    }

    function order_process() {
        $this->layout = false;
        $custom = $this->data['custom'];
        $cart_ids = explode("|", $custom);
        $shipping_cost = $this->data['shipping_cost'];
        foreach ($cart_ids as $cart_id) {
            $conditions['Cart.id'] = $cart_id;
            $this->Cart->Behaviors->attach('Containable');
            $this->Cart->contain('Shipping.shipping_method', 'User.id', 'User.Country.name', 'User.State.name', 'User.City.name', 'Product.products_weight', 'Product.id', 'Product.user_id', 'Product.category_id', 'Product.products_title', 'Product.products_price', 'Product.products_quantity', 'Product.use_paypal', 'Product.use_google_checkout', 'Product.tax_us', 'Product.products_commission', 'Product.products_commissionType', 'Product.ProductShipping', 'Product.ProductShipping.Shipping', 'Product.ProductInternationalShipping.Shipping', 'Product.ProductInternationalShipping', 'Product.Salestax', 'Product.User.username');
            $carts[$cart_id] = $this->Cart->find("all", array("conditions" => $conditions));
        }

        $pay_to_id = $this->data['sellerID'];
        $paymentsGateway = $this->Paymentmethod->find("first", array("conditions" => array("Paymentmethod.user_id" => $pay_to_id, "Paymentmethod.methodname" => "Paypal")));
        //pr($paymentsGateway);
        $this->set(compact('shipping_cost', 'custom', 'carts', 'paymentsGateway'));
        $this->Render("paypal_direct");
    }

    function order_process_gcheckout() {
        //$this->layout="carthome";
        $this->layout = false;
        $custom = $this->data['custom'];
        $MerchantPrivateData = array("cart-id" => $custom);
        $cart_ids = explode("|", $custom);
        $shipping_cost = $this->data['shipping_cost'];
        foreach ($cart_ids as $cart_id) {
            $conditions['Cart.id'] = $cart_id;
            $this->Cart->Behaviors->attach('Containable');
            $this->Cart->contain('Shipping.shipping_method', 'User.id', 'User.Country.name', 'User.State.name', 'User.City.name', 'Product.products_weight', 'Product.products_description', 'Product.id', 'Product.user_id', 'Product.category_id', 'Product.products_title', 'Product.products_price', 'Product.products_quantity', 'Product.use_paypal', 'Product.use_google_checkout', 'Product.tax_us', 'Product.products_commission', 'Product.products_commissionType', 'Product.ProductShipping', 'Product.ProductShipping.Shipping', 'Product.ProductInternationalShipping.Shipping', 'Product.ProductInternationalShipping', 'Product.Salestax', 'Product.User.username');
            $carts = $this->Cart->find("all", array("conditions" => $conditions));
            $this->GoogleCheckout->setItem($carts[0]['Product']['products_title'], $carts[0]['Product']['products_description'], $carts[0]['Cart']['quantity'], $carts[0]['Cart']['product_cost'], $MerchantPrivateData, $MerchantPrivateData);
            $this->GoogleCheckout->setItem("Sales tax", "Sales tax for: " . $carts[0]['Product']['products_title'], "1", $carts[0]['Cart']['sales_tax'], $MerchantPrivateData, $MerchantPrivateData);
        }
        $this->GoogleCheckout->setItem("Shipping & handling", $this->data['shipping_method'], "1", $shipping_cost, $MerchantPrivateData, $MerchantPrivateData);

        $pay_to_id = $this->data['sellerID'];
        $this->Session->write('payToId', $pay_to_id);
        //$paymentsGateway=$this->Paymentmethod->find("first",array("conditions"=>array("Paymentmethod.user_id"=>$pay_to_id,"Paymentmethod.methodname"=>"Paypal")));

        $gcheckout = $this->GoogleCheckout->generateCartButton($MerchantPrivateData);
        $this->set(compact('gcheckout'));
    }

    function order_list() {
        $this->Cart->recursive = 2;
        $conditions = array("Cart.user_id" => $this->Auth->User('id'), 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
        $orders = array("Cart.add_date" => "DESC");
        $total = $this->Cart->find("count", array("conditions" => $conditions));
        $sum = $this->Cart->find("first", array("conditions" => $conditions, 'fields' => array('sum((Cart.product_cost*Cart.quantity)+Cart.sales_tax+Cart.shipping_cost) AS total')));
        $this->Cart->Behaviors->attach('Containable');

        $this->Cart->contain('Order.id', 'Order.transaction_id', 'Shipping.shipping_method', 'Product.id', 'Product.user_id', 'Product.User.first_name', 'Product.User.last_name', 'Product.category_id', 'Product.products_title', 'Product.products_thumbnailImage', 'User.id', 'User.first_name', 'User.last_name');
        $this->paginate = array('limit' => 10, "conditions" => $conditions, "order" => $orders);
        $this->set('carts', $this->paginate('Cart'));
        $this->set(compact('total', 'sum'));
        $this->layout = "innerhome";
    }

    function view_invoice($id=null) {
        $conditions = array("Cart.id" => $id, 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
        $this->Cart->Behaviors->attach('Containable');
        $this->Cart->contain('Order.id', 'Order.transaction_id', 'Order.payment_status', 'Order.shipping_status', 'Order.add_date', 'Shipping.shipping_method', 'Product.id', 'Product.user_id', 'Product.category_id', 'Product.products_title', 'Product.products_thumbnailImage', 'Product.User.first_name', 'Product.User.last_name', 'User.id', 'User.first_name', 'User.last_name');
        $carts = $this->Cart->find("all", array("conditions" => $conditions));
        $this->set(compact('carts'));
        $this->layout = false;
    }

    function fetch_shipping_method($id=null) {
        $this->layout = false;
        return $sm = $this->Shipping->findById($id);
        $this->autoRender = false;
    }

    function totalitem_cart() {
        $this->layout = null;
        $this->autoRender = false;
        if ($this->Auth->User('id'))
            $conditions = array("Cart.user_id" => $this->Auth->User('id'), 'Cart.product_id >' => 0, 'Cart.payment_status' => 0, 'Cart.status' => 1);
        else
            $conditions = array('Cart.unique_id' => $uniqueIDCoookie, 'Cart.product_id >' => 0, 'Cart.payment_status' => 0, 'Cart.status' => 0);
        return $this->Cart->find("count", array("conditions" => $conditions));
    }

}

?>